<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8" %> <%@ taglib prefix="c"
                                            uri="http://java.sun.com/jsp/jstl/core" %> <%@ taglib prefix="fmt"
                                                                                                  uri="http://java.sun.com/jsp/jstl/fmt" %> <% String path =
        request.getContextPath(); String basePath = request.getScheme() + "://" +
        request.getServerName() + ":" + request.getServerPort() + path + "/"; %>
<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <base href="<%=basePath%>" />
  <title>茶叶进销存系统 - 新增采购单</title>
  <link rel="stylesheet" href="css/global.css" />
  <link
          rel="stylesheet"
          href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.3/css/all.min.css"
  />
  <style>
    .form-container {
      max-width: 1200px;
      margin: 0 auto;
      padding: 20px;
    }
    .form-group {
      margin-bottom: 20px;
    }
    .form-group label {
      display: block;
      margin-bottom: 8px;
      font-weight: 500;
      color: var(--text-regular);
    }
    .form-control {
      width: 100%;
      padding: 10px 15px;
      border: 1px solid var(--border-color);
      border-radius: 4px;
      font-size: 14px;
      transition: all 0.3s;
      background-color: #fff;
    }
    .form-control:focus {
      outline: none;
      border-color: var(--primary-color);
      box-shadow: 0 0 0 2px rgba(139, 158, 107, 0.2);
    }
    .btn-group {
      display: flex;
      justify-content: flex-end;
      gap: 15px;
      margin-top: 30px;
    }
    .tea-icon {
      color: var(--primary-color);
      margin-right: 5px;
    }
    .form-header {
      font-size: 18px;
      color: var(--text-regular);
      margin-bottom: 20px;
      padding-bottom: 10px;
      border-bottom: 1px solid var(--border-color);
    }
    .form-row {
      display: flex;
      gap: 20px;
    }
    .form-col {
      flex: 1;
    }
    .purchase-item {
      background: #f8f9fa;
      border: 1px solid var(--border-color);
      border-radius: 8px;
      padding: 20px;
      margin-bottom: 15px;
      position: relative;
    }
    .item-remove-btn {
      position: absolute;
      top: 10px;
      right: 10px;
      background: var(--danger-color);
      color: white;
      border: none;
      border-radius: 50%;
      width: 30px;
      height: 30px;
      cursor: pointer;
      display: flex;
      align-items: center;
      justify-content: center;
    }
    .total-summary {
      background: var(--primary-color);
      color: white;
      padding: 20px;
      border-radius: 8px;
      text-align: center;
      margin-bottom: 20px;
    }
    .total-amount {
      font-size: 24px;
      font-weight: bold;
      margin-bottom: 10px;
    }
    .item-subtotal {
      font-weight: bold;
      color: var(--success-color);
    }
    .price-display {
      margin-top: 5px;
      font-size: 12px;
      color: var(--text-secondary);
    }
  </style>
</head>
<body>
<div class="app-container">
  <!-- 侧边栏 -->
  <div class="sidebar" id="sidebar">
    <div class="sidebar-logo" onclick="toggleSidebar()">
      <span><i class="fas fa-leaf tea-icon"></i> 茶叶进销存系统</span>
    </div>

    <div class="sidebar-menu">
      <div class="menu-item" onclick="location.href='views/home.jsp'">
        <i class="fas fa-home"></i>
        <span>系统首页</span>
      </div>
      <div class="menu-item" onclick="location.href='TeaServlet'">
        <i class="fas fa-coffee"></i>
        <span>茶叶管理</span>
      </div>
      <div class="menu-item" onclick="location.href='CategoryServlet'">
        <i class="fas fa-tags"></i>
        <span>分类管理</span>
      </div>
      <div class="menu-item" onclick="location.href='WarehouseServlet'">
        <i class="fas fa-boxes"></i>
        <span>仓库管理</span>
      </div>
      <div class="menu-item" onclick="location.href='OrderServlet'">
        <i class="fas fa-receipt"></i>
        <span>订单管理</span>
      </div>
      <div class="menu-item" onclick="location.href='LogisticsServlet'">
        <i class="fas fa-shipping-fast"></i>
        <span>物流管理</span>
      </div>
      <div class="menu-item" onclick="location.href='SupplierServlet'">
        <i class="fas fa-truck"></i>
        <span>供应商管理</span>
      </div>
      <div
              class="menu-item active"
              onclick="location.href='<%=basePath%>purchase/list'"
      >
        <i class="fas fa-truck"></i>
        <span>采购管理</span>
      </div>
      <div class="menu-item" onclick="location.href='CustomerServlet'">
        <i class="fas fa-users"></i>
        <span>客户管理</span>
      </div>
      <div class="menu-item" onclick="location.href='AddressServlet'">
        <i class="fas fa-map-marker-alt"></i>
        <span>地址管理</span>
      </div>
    </div>
  </div>

  <!-- 主内容区 -->
  <div class="main-content">
    <!-- 顶部导航栏 -->
    <div class="navbar">
      <div class="navbar-left">
        <h3><i class="fas fa-plus-circle tea-icon"></i> 新增采购单</h3>
      </div>
      <div class="navbar-right">
            <span
            ><i class="fas fa-user tea-icon"></i> 欢迎，${ username}管理员</span
            >
        <a href="LogoutServlet" class="el-link el-link--danger ml-10"
        ><i class="fas fa-sign-out-alt"></i> 退出</a
        >
      </div>
    </div>

    <!-- 内容卡片 -->
    <div class="el-card">
      <div class="el-card__header">
        <span><i class="fas fa-info-circle tea-icon"></i> 采购单信息</span>
        <div>
          <a href="purchase/list" class="el-button">
            <i class="fas fa-arrow-left"></i> 返回列表
          </a>
        </div>
      </div>
      <div class="el-card__body">
        <form
                action="purchase/save"
                method="post"
                class="form-container"
                id="purchaseForm"
        >
          <div class="form-header">
            <i class="fas fa-info-circle tea-icon"></i> 基本信息
          </div>

          <div class="form-row">
            <div class="form-col">
              <div class="form-group">
                <label for="supplierId"
                ><i class="fas fa-truck tea-icon"></i> 供应商</label
                >
                <select
                        id="supplierId"
                        name="supplierId"
                        class="form-control"
                        required
                >
                  <option value="" hidden="hidden">请选择供应商</option>
                  <c:forEach items="${suppliers}" var="supplier">
                    <option value="${supplier.supplier_id}">
                        ${supplier.supplier_name}
                    </option>
                  </c:forEach>
                </select>
              </div>
            </div>
            <div class="form-col">
              <div class="form-group">
                <label for="warehouseId"
                ><i class="fas fa-warehouse tea-icon"></i> 入库仓库</label
                >
                <select
                        id="warehouseId"
                        name="warehouseId"
                        class="form-control"
                        required
                >
                  <option value="" hidden="hidden">请选择仓库</option>
                  <c:forEach items="${warehouses}" var="warehouse">
                    <option value="${warehouse.warehouse_id}">
                        ${warehouse.warehouse_name}
                    </option>
                  </c:forEach>
                </select>
              </div>
            </div>
          </div>

          <!-- 金额汇总 -->
          <div class="total-summary">
            <div class="total-amount" id="totalAmount">¥0.00</div>
            <div>共 <span id="itemCount">0</span> 个采购项目</div>
          </div>

          <div class="form-header">
            <i class="fas fa-list tea-icon"></i> 采购项目
            <button
                    type="button"
                    class="el-button el-button--success"
                    onclick="addPurchaseItem()"
                    style="float: right"
            >
              <i class="fas fa-plus"></i> 添加项目
            </button>
          </div>

          <div id="purchaseItems">
            <!-- 采购项目将通过JavaScript动态添加 -->
          </div>

          <div
                  id="emptyMessage"
                  style="
                  text-align: center;
                  padding: 40px 0;
                  color: var(--text-secondary);
                "
          >
            <i
                    class="fas fa-inbox"
                    style="font-size: 36px; margin-bottom: 15px; opacity: 0.5"
            ></i>
            <p>暂无采购项目，点击"添加项目"按钮开始添加</p>
          </div>

          <div class="btn-group">
            <button
                    type="button"
                    class="el-button"
                    onclick="history.back()"
            >
              <i class="fas fa-times"></i> 取消
            </button>
            <button type="submit" class="el-button el-button--primary">
              <i class="fas fa-save"></i> 保存采购单
            </button>
          </div>
        </form>
      </div>
    </div>
  </div>
</div>

<script>
  let isCollapsed = false;
  let itemIndex = 0;

  const teas = [
    <c:forEach items="${teas}" var="tea" varStatus="status">
    {
      id: ${tea.tea_id},
      name: '${tea.tea_name}',
      price: ${tea.price},
      unit: '${tea.unit}'
    }<c:if test="${!status.last}">,</c:if>
    </c:forEach>
  ];

  function toggleSidebar() {
    const sidebar = document.getElementById('sidebar');
    isCollapsed = !isCollapsed;
    sidebar.classList.toggle('collapsed', isCollapsed);
    localStorage.setItem('sidebarCollapsed', isCollapsed);
  }

  function addPurchaseItem() {
    const itemsContainer = document.getElementById('purchaseItems');
    const emptyMessage = document.getElementById('emptyMessage');

    // Generate tea options
    let teaOptions = '<option value="">请选择茶叶</option>';
    for (let i = 0; i < teas.length; i++) {
      teaOptions += '<option value="' + teas[i].id + '" data-price="' + teas[i].price + '" data-unit="' + teas[i].unit + '">' + teas[i].name + '</option>';
    }

    const itemHtml = '<div class="purchase-item" id="item-' + itemIndex + '">' +
            '<button type="button" class="item-remove-btn" onclick="removePurchaseItem(' + itemIndex + ')" title="删除项目">' +
            '<i class="fas fa-times"></i>' +
            '</button>' +
            '<div class="form-row">' +
            '<div class="form-col">' +
            '<div class="form-group">' +
            '<label>茶叶</label>' +
            '<select name="teaId" class="form-control" onchange="updateItemPrice(' + itemIndex + ')" required>' +
            teaOptions +
            '</select>' +
            '<div class="price-display" id="priceDisplay-' + itemIndex + '"></div>' +
            '</div>' +
            '</div>' +
            '<div class="form-col">' +
            '<div class="form-group">' +
            '<label>数量</label>' +
            '<input type="number" name="quantity" class="form-control" min="0.01" step="0.01" placeholder="0.00" onchange="calculateSubtotal(' + itemIndex + ')" required>' +
            '</div>' +
            '</div>' +
            '<div class="form-col">' +
            '<div class="form-group">' +
            '<label>单价</label>' +
            '<input type="number" name="unitPrice" class="form-control" min="0.01" step="0.01" placeholder="0.00" onchange="calculateSubtotal(' + itemIndex + ')" required>' +
            '</div>' +
            '</div>' +
            '<div class="form-col">' +
            '<div class="form-group">' +
            '<label>小计</label>' +
            '<div class="form-control item-subtotal" id="subtotal-' + itemIndex + '">¥0.00</div>' +
            '</div>' +
            '</div>' +
            '</div>' +
            '</div>';

    itemsContainer.insertAdjacentHTML('beforeend', itemHtml);
    emptyMessage.style.display = 'none';
    itemIndex++;
    updateItemCount();
  }

  function updateItemPrice(index) {
    const itemRow = document.getElementById('item-' + index);
    if (!itemRow) return; // Check if item exists

    const teaSelect = itemRow.querySelector('select[name="teaId"]');
    const unitPriceInput = itemRow.querySelector('input[name="unitPrice"]');
    const priceDisplay = document.getElementById('priceDisplay-' + index);

    const selectedOption = teaSelect.options[teaSelect.selectedIndex];
    if (selectedOption.value) {
      const price = selectedOption.getAttribute('data-price');
      const unit = selectedOption.getAttribute('data-unit');
      unitPriceInput.value = parseFloat(price).toFixed(2);

      // Display price and unit information
      priceDisplay.textContent = price + '元/' + unit;
      priceDisplay.style.display = 'block';

      calculateSubtotal(index);
    } else {
      priceDisplay.textContent = '';
      priceDisplay.style.display = 'none';
    }
  }

  function calculateSubtotal(index) {
    const itemRow = document.getElementById('item-' + index);
    if (!itemRow) return; // Check if item exists

    const quantityInput = itemRow.querySelector('input[name="quantity"]');
    const unitPriceInput = itemRow.querySelector('input[name="unitPrice"]');
    const subtotalDiv = document.getElementById('subtotal-' + index);

    const quantity = parseFloat(quantityInput.value) || 0;
    const unitPrice = parseFloat(unitPriceInput.value) || 0;
    const subtotal = quantity * unitPrice;

    subtotalDiv.textContent = '¥' + subtotal.toFixed(2);
    calculateTotal();
  }

  function calculateTotal() {
    const itemsContainer = document.getElementById('purchaseItems');
    const items = itemsContainer.children;
    let total = 0;

    for (let i = 0; i < items.length; i++) {
      const item = items[i];
      const quantityInput = item.querySelector('input[name="quantity"]');
      const unitPriceInput = item.querySelector('input[name="unitPrice"]');

      const quantity = parseFloat(quantityInput.value) || 0;
      const unitPrice = parseFloat(unitPriceInput.value) || 0;
      total += quantity * unitPrice;
    }

    document.getElementById('totalAmount').textContent = '¥' + total.toFixed(2);
  }

  function removePurchaseItem(index) {
    const itemRow = document.getElementById('item-' + index);
    if (!itemRow) return; // Check if item exists

    itemRow.remove();

    updateItemCount();
    calculateTotal();

    const itemsContainer = document.getElementById('purchaseItems');
    const emptyMessage = document.getElementById('emptyMessage');
    if (itemsContainer.children.length === 0) {
      emptyMessage.style.display = 'block';
    }
  }

  function updateItemCount() {
    const itemsContainer = document.getElementById('purchaseItems');
    const count = itemsContainer.children.length;
    document.getElementById('itemCount').textContent = count;
  }

  window.onload = function() {
    const savedState = localStorage.getItem('sidebarCollapsed');
    if(savedState === 'true') {
      document.getElementById('sidebar').classList.add('collapsed');
      isCollapsed = true;
    }

    document.getElementById('purchaseForm').addEventListener('submit', function(e) {
      const itemsContainer = document.getElementById('purchaseItems');
      if (itemsContainer.children.length === 0) {
        e.preventDefault();
        alert('请至少添加一个采购项目');
        return false;
      }

      const items = itemsContainer.children;
      for (let i = 0; i < items.length; i++) {
        const item = items[i];
        const teaSelect = item.querySelector('select[name="teaId"]');
        const quantityInput = item.querySelector('input[name="quantity"]');
        const unitPriceInput = item.querySelector('input[name="unitPrice"]');

        if (!teaSelect.value || !quantityInput.value || !unitPriceInput.value) {
          e.preventDefault();
          alert('请完整填写所有采购项目信息');
          return false;
        }
      }
    });

    addPurchaseItem();
  }
</script>
</body>
</html>